package com.app.micaihu.view.newsdetail;


import android.content.Intent;
import android.content.res.Configuration;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.android.volley.VolleyError;
import com.app.base.BaseActivity;
import com.app.config.LoadViewConfig;
import com.app.micaihu.R;
import com.app.micaihu.adapter.PagerAdapter.CommonFragmentAdapter;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.bean.news.VideoRoom;
import com.app.micaihu.bean.news.VideoRoomNewsList;
import com.app.micaihu.bean.news.VideoShow;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.custom.view.HackyViewPager;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.utils.AppShareUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.videoplayer.JCVideoPlayer;
import com.app.micaihu.view.newsdetail.fragment.VideoShowFragment2;
import com.app.utils.scrollablelayout.ScrollableHelper;
import com.app.utils.scrollablelayout.ScrollableLayout;
import com.app.utils.stickheaderview.tab.SlidingTabLayout;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.image.LoadImageUtils;
import com.app.widget.LoadView;
import com.blankj.utilcode.util.BarUtils;
import com.google.gson.reflect.TypeToken;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Guo on 2017/1/4.
 * <p>
 * 视频专栏
 */
public class VideoShowActivity extends BaseActivity implements View.OnClickListener, ScrollableLayout.OnScrollListener {

    private SlidingTabLayout navTab;
    private String id;

    private VideoRoomNewsList videoRoomNewsList;
    private ArrayList<Fragment> fragments;
    private LoadView loadView;
    private CustomImageView civHeader;
    private TextView tvDesc;
    private TextView tvTitle;
    private VideoRoom videoRoom;
    private AppShareUtils mShareUtils;
    private View mHeadAuthorView;
    private TextView authorView;
    private CustomImageView civ;
    private TranslateAnimation enterAnimation;
    private TranslateAnimation outAnimation;
    private int navTabScrollX;
    private CommonFragmentAdapter mAdapter;
    private HackyViewPager mViewPager;
    private ScrollableLayout scrollableLayout;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_videoshow;
    }

    @Override
    protected void setData() {
        BarUtils.addMarginTopEqualStatusBarHeight(findViewById(R.id.head_layout));
        initView();
        loadData();
    }

    @Override
    protected void addListeners() {

    }

    /*
     * 返回
     */
    public void doBack(View view) {
        finish();
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            //判断是否有视频全屏
            return;
        }
        finish();
        overridePendingTransition(0, R.anim.base_slide_right_out);
    }


    @Override
    protected void onPause() {
        super.onPause();
        //释放播放器资源
        JCVideoPlayer.releaseAllVideos();

    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            if (navTab != null && navTabScrollX > 0) {
                navTab.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        navTab.scrollTo(navTabScrollX, 0);
                    }
                }, 200);
            }

        } else {
            if (navTab != null) {
                navTabScrollX = navTab.getScrollX();

            }

        }
    }


    /**
     * 初始化页面
     */
    private void initView() {
        //获取页面数据
        Intent intent = getIntent();
        if (intent == null) {
            onBackPressed();
            ToastUtils.makeText("页面异常");
            return;
        }
        id = getIntent().getStringExtra(Config.Extra.PARAMETER1);

        mViewPager = (HackyViewPager) findViewById(R.id.view_pager);
        navTab = (SlidingTabLayout) findViewById(R.id.navig_tab);
        loadView = (LoadView) findViewById(R.id.ld_loadview);
        loadView.setErrorPageClickListener(this);
        civHeader = (CustomImageView) findViewById(R.id.cv_icon);
        tvDesc = (TextView) findViewById(R.id.tv_desc);
        tvTitle = (TextView) findViewById(R.id.tv_title);

        ImageView ivFunction = (ImageView) findViewById(R.id.page_head_function);
        ivFunction.setImageResource(R.drawable.detail_share_black_selector);
        ivFunction.setVisibility(View.VISIBLE);
        ivFunction.setOnClickListener(this);

        mHeadAuthorView = findViewById(R.id.page_head_author_layout);
        mHeadAuthorView.setOnClickListener(this);
        authorView = (TextView) mHeadAuthorView.findViewById(R.id.page_head_author);
        civ = (CustomImageView) mHeadAuthorView.findViewById(R.id.page_head_usericon);


        scrollableLayout = (ScrollableLayout) findViewById(R.id.scrollableLayout);
        scrollableLayout.setOnScrollListener(this);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (scrollableLayout != null && fragments != null) {
                    scrollableLayout.getHelper().setCurrentScrollableContainer((ScrollableHelper.ScrollableContainer) fragments.get(position));
                }
                //释放播放器资源
                JCVideoPlayer.releaseAllVideos();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }


    /**
     * 加载数据
     */
    private void loadData() {
        Map<String, String> parms = new HashMap<>();
        parms.put("id", id);
        HttpListener<DataBean<VideoRoomNewsList>> httpListener = new HttpListener<DataBean<VideoRoomNewsList>>() {

            @Override
            public void onStart() {
//                LogUtils.e("gzq", "onStart");
                if (loadView != null) {
                    loadView.showLoadPage("");
                }
            }

            @Override
            public void onError(VolleyError error) {
                if (loadView != null) {
                    loadView.showErrorPage();
                }
            }

            @Override
            public void onSuccess(DataBean<VideoRoomNewsList> response) {

                if (response.noErrorData()) {
                    videoRoomNewsList = response.getData();
                    setData1();
                } else {
                    loadView.showErrorPage();
                }
            }

        };
        HttpUtils.addPostCacheRequest(URIContant.VIDEO_ROOM, new TypeToken<DataBean<VideoRoomNewsList>>() {
        }.getType(), "", parms, httpListener);

    }


    /**
     * 设置数据
     */
    private void setData1() {
        List<VideoShow> videoShowList = videoRoomNewsList.getSetList();
        List<NewsEntity> newsList = videoRoomNewsList.getNewsList();
        VideoRoom columnInfo = videoRoomNewsList.getColumnInfo();
        if (columnInfo != null) {
            setHeaderData(columnInfo);
        }
        if (videoShowList != null && !videoShowList.isEmpty() && columnInfo != null) {
            if (fragments == null) {
                fragments = new ArrayList<>();
            }
            fragments.clear();

            for (int i = 0; i < videoShowList.size(); i++) {
                VideoShowFragment2 videoShowFragment2 = VideoShowFragment2.newInstance(id, videoShowList.get(i).getSetNum());

                if (i == 0 && newsList != null) {
                    videoShowFragment2.initData(newsList);
                }
                fragments.add(videoShowFragment2);
            }

            if (mAdapter == null) {
                String[] titles = new String[videoShowList.size()];
                for (int i = 0; i < videoShowList.size(); i++) {
                    if (videoShowList.get(i) != null) {
                        titles[i] = videoShowList.get(i).getSetTitle();
                    }
                }
                mAdapter = new CommonFragmentAdapter(getSupportFragmentManager(), fragments, titles);
                mViewPager.setAdapter(mAdapter);
//                mViewPager.setOffscreenPageLimit(0);


                navTab.setViewPager(mViewPager);

                scrollableLayout.getHelper().setCurrentScrollableContainer((ScrollableHelper.ScrollableContainer) fragments.get(0));
                mViewPager.setCurrentItem(0);
                navTab.setTabSelected(0);
            }
            loadView.showSuccess();
        } else {
            loadView.showEmptyPage(LoadViewConfig.EMPTY_DEFAULT, AppApplication.getInstance().getString(R.string.vidoe_empty));
        }
    }


    private void setHeaderData(VideoRoom columnInfo) {
        setShareData(columnInfo);
        LoadImageUtils.getInstance().loadListCircleImage(civHeader, columnInfo.getIcon());
        tvDesc.setText(columnInfo.getDesc());
        tvTitle.setText(columnInfo.getTitle());
        LoadImageUtils.getInstance().loadCircleImage(civ, columnInfo.getIcon());
        authorView.setText(columnInfo.getTitle());

    }


    /**
     * 设置分享的数据
     *
     * @param videoRoom
     */
    public void setShareData(VideoRoom videoRoom) {
        this.videoRoom = videoRoom;
    }


    @Override
    public void onClick(View v) {
        if (v == null) {
            return;
        }
        switch (v.getId()) {
            case R.id.page_head_function:
                share();

                break;

            case R.id.error_page:// 重新加载页面数据

                loadData();
                break;
            case R.id.page_head_author_layout:
//                if(viewPagerChangeListener != null && mAdapter != null && mHeader != null){
//                    int position = viewPagerChangeListener.getPosition();
//                    SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mAdapter.getScrollTabHolders();
//                    ScrollTabHolder scrollTabHolder = scrollTabHolders.valueAt(position);
//                    scrollTabHolder.adjustScroll((int) (mHeader.getHeight() + mHeader.getTranslationY()), mHeader.getHeight());
//                }
                break;
            default:

                break;
        }
    }


    /**
     * 分享
     */
    private void share() {
        if (mShareUtils == null) {
            mShareUtils = new AppShareUtils(this);
        }
        mShareUtils.showShareDialog(this.videoRoom, "");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (data != null) {
                UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 滑动头部动画
     */
    private void scrollHeadAnimotion(boolean in) {
        if (mHeadAuthorView == null) {
            return;
        }
        if (in && mHeadAuthorView.getVisibility() == View.GONE) {

            if (enterAnimation == null) {
                enterAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                        -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
                enterAnimation.setDuration(300);
                enterAnimation.setFillAfter(true);
            }
            mHeadAuthorView.startAnimation(enterAnimation);
            mHeadAuthorView.setVisibility(View.VISIBLE);

        } else if (!in && mHeadAuthorView.getVisibility() == View.VISIBLE) {
            if (outAnimation == null) {
                outAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                        0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                        -1.0f);
                outAnimation.setDuration(300);
                outAnimation.setFillAfter(true);
            }
            mHeadAuthorView.startAnimation(outAnimation);
            mHeadAuthorView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onScroll(int currentY, int maxY) {
        scrollHeadAnimotion(currentY > maxY / 2);
    }


}
